/*
 * Copyright 2012 Gregor Schauer
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package at.schauer.gregor.vienna.identifier;

import at.schauer.gregor.vienna.exception.IdentifierGenerationException;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.reflect.FieldUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Gregor Schauer
 */
public class PropertiesStringGenerator<O> implements IdentifierGenerator<String, O> {
	protected String separator;
	protected List<String> properties = new ArrayList<String>();

	public PropertiesStringGenerator(String... properties) {
		this(" ", properties);
	}

	public PropertiesStringGenerator(String separator, String... properties) {
		this.separator = separator;
		CollectionUtils.addAll(this.properties, properties);
	}

	@Override
	public String generate(O obj) {
		StringBuilder builder = new StringBuilder();
		for (String property : properties) {
			try {
				builder.append(separator).append(PropertyUtils.getProperty(obj, property));
			} catch (Exception e) {
				try {
					builder.append(separator).append(FieldUtils.readField(obj, property, true));
				} catch (Exception ignored) {
					throw new IdentifierGenerationException(e);
				}
			}
		}
		return builder.length() > 0 ? builder.substring(1) : "";
	}

	public List<String> getProperties() {
		return properties;
	}

	public void setProperties(List<String> properties) {
		this.properties = properties;
	}
}
